package com.itheima.reggie.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    /**
     * @author: 陈家乐
     * @email：68668646@qq.com
     * @date: 2023/2/12 15:26
     */
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     *
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        log.info("订单数据：{}", orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }

    @GetMapping("/userPage")
    public R<Page> page(int page, int pageSize) {
        Page pageInfo = new Page(page, pageSize);
        orderService.page(pageInfo);
        return R.success(pageInfo);
    }

    /**
     * 订单分页查询
     *
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("page")
    public R<Page> orderManagement(Integer page, Integer pageSize, Long number, String beginTime, String endTime) {
        //构造分页构造器对象
        Page<Orders> pageBean = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.ge(beginTime != null, Orders::getOrderTime, beginTime);
        wrapper.le(endTime != null, Orders::getCheckoutTime, endTime);
        wrapper.like(number != null, Orders::getNumber, number);
        orderService.page(pageBean, wrapper);
        return R.success(pageBean);
    }

    /**
     * 订单派送
     *
     * @param orders
     * @return
     */
    @PutMapping
    public R update(@RequestBody Orders orders) {
        Orders order = orderService.getById(orders.getId());
        order.setStatus(orders.getStatus());
        orderService.updateById(order);
        return R.success("修改成功");
    }
    @GetMapping("/export")
    public R importExcel(){
        List<OrderDetail> list = orderDetailService.list();
        ExcelWriterBuilder work= EasyExcel.write("/Users/chenjiale/Desktop/testexcel/order.xlsx",OrderDetail.class);
        work.sheet("导出订单明细表").doWrite(list);

        return R.success("导出成功！");
    }
}
